package com.yingsheng.bi.hks.basic.utils;

import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicReference;

@Component
public class AppContext implements ApplicationContextAware {

    private static final AtomicReference<ApplicationContext> CONTEXT = new AtomicReference<>();

    @Override
    public void setApplicationContext(@NotNull ApplicationContext applicationContext) throws BeansException {
        CONTEXT.set(applicationContext);
    }

    private static ApplicationContext getContext() {
        ApplicationContext applicationContext = CONTEXT.get();
        if (applicationContext == null) {
            throw new IllegalStateException("ApplicationContext not initialized");
        }
        return applicationContext;
    }

    private static Environment getEnvironment() {
        ApplicationContext applicationContext = getContext();
        return applicationContext.getEnvironment();
    }

    public static <T> T getBean(Class<T> beanType) {
        ApplicationContext applicationContext = getContext();
        return applicationContext.getBean(beanType);
    }

    public static String getProperty(String key) {
        Environment environment = getEnvironment();
        return environment.getProperty(key);
    }

    public static String getProperty(String key, String defaultValue) {
        Environment environment = getEnvironment();
        return environment.getProperty(key, defaultValue);
    }

    public static <T> T getProperty(String key, Class<T> targetType, T defaultValue) {
        Environment environment = getEnvironment();
        return environment.getProperty(key, targetType, defaultValue);
    }


}
